package com.cloud.controller.system;

import com.cloud.model.system.SysResource;
import com.cloud.model.system.SysRole;
import com.cloud.model.system.SysUser;
import com.cloud.service.SysUserService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.PostMapping;

import javax.validation.Valid;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * Created by ju on 2017/3/27.
 */
//@RestController
@Controller
public class LoginController {
    protected final Logger logger = LoggerFactory.getLogger(this.getClass());
    @Autowired
    private SysUserService sysUserService;

    @PostMapping(value = "login")
    public String login(@Valid SysUser sysUser, BindingResult bindingResult, boolean rememberMe) throws Exception {
        if (bindingResult.hasErrors()) {
            throw new IllegalArgumentException("");
            //return ResultUtils.error("登录信息输入不全");
        }
        try {
            UsernamePasswordToken token = new UsernamePasswordToken(sysUser.getUserName(), sysUser.getUserPassword(), rememberMe);
            Subject subject = SecurityUtils.getSubject();
            Session session = subject.getSession();
            subject.login(token);
            sysUser = sysUserService.findUserByUserName(sysUser.getUserName());
            session.setAttribute("user", sysUser);
          //  session.setAttribute("resources", getResources(sysUser));
            logger.info("{}  Login Sussesful", sysUser.getUserName());
            //return ResultUtils.success("登录成功", "{'sessionId':"+session.getId()+"}");
            return "home";
        } catch (UnknownAccountException e) {
            logger.error("{} 登录失败=={未注册账户}", sysUser.getUserName());
            throw new IllegalArgumentException("未注册账户");
            //return ResultUtils.error("未知账户");
        } catch (IncorrectCredentialsException e) {
            logger.error("{} 登录失败=={输入密码不正确}", sysUser.getUserName());
            throw new IllegalArgumentException("输入密码不正确");
            // return ResultUtils.error("密码不正确");
        } catch (LockedAccountException e) {
            logger.error("{} 登录失败=={账户被锁定，无法登录}", sysUser.getUserName());
            throw new IllegalArgumentException("账户被锁定，无法登录");
            // return ResultUtils.error("账户已被锁定");
        } catch (ExcessiveAttemptsException e) {
            logger.error("{} 登录失败=={密码输入超限制}", sysUser.getUserName());
            throw new IllegalArgumentException("密码输入超过限定次数，用户被锁定！");
            //  return ResultUtils.unauthorized("密码输入超过限定次数，用户被锁定！");
        } catch (AuthenticationException e) {
            logger.error("{} 登录失败=={用户或者密码不正确}", sysUser.getUserName());
            throw new IllegalArgumentException("用户或者密码不正确");
            // return ResultUtils.error("用户或者密码不正确！");
        } catch (Exception e) {
            logger.error("{} 登录失败=={}", sysUser.getUserName(), e.getMessage());
            throw new IllegalArgumentException("未知错误");
            //  return ResultUtils.error(SystemConstant.UNKNOW_ERROR, "未知错误");
        }
    }

    private static List<SysResource> getResources(SysUser sysUser) {
        if (sysUser != null) {
            Set<SysResource> resourceSet = new HashSet<>();
            if (!sysUser.getRoles().isEmpty()) {
                for (SysRole role : sysUser.getRoles()) {
                    for (SysResource resource : role.getSysresources()) {
                        resourceSet.add(resource);
                    }
                }
            }
            return new ArrayList<>(resourceSet);
        }
        return null;
    }
}
